import { useState, useEffect } from 'react'
import style from './index.module.scss'
import HeaderView from '@/components/Header/index'
import Bottom from '@/components/Bottom/index'
import LoadingView from '@/components/Loading/index'
import { CartList, UpdateNum, DeleteProduct, checkedCart } from '@/api/shopcart'
import { Checkbox, Toast, Image, Stepper, Button, SwipeAction, Dialog } from 'antd-mobile'
import useSyncState from '@/utils/tongbu'
import { itemType } from './type'
import { cartNumAsync } from '@/reduxToolkit/reducers/cartNum'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { useActivate, useUnactivate } from 'react-activation'


const ShopCart = () => {
  const [flag, setFlag] = useState(true)
  const [loadingCode, setLoadingCode] = useState(1)  
  const [list, setList] = useSyncState([]) // 购物车产品
  const [value, setValue] = useSyncState([]) // 产品复选框
  const [total, setTotal] = useState(0) // 产品复选框
  const [checkAll, setCheckAll] = useState(false) // 是否全选
  const [count, setCount] = useState(0)
  const cartNum = useSelector((state: {cartNum: {value: number}}) => state.cartNum.value)
  type CheckboxValue = string | number
  const dispatch: any = useDispatch()
  const navigate = useNavigate()

  // 总价
  const totalPrice = (list: [], value: CheckboxValue[]) => {
    let sum = 0
    list.filter((item: {id: number}) => value.includes(item.id)).forEach((itemB: {goods: {price: number}, num: number}) => {
      return sum += itemB.goods.price * itemB.num
    })
    setTotal(sum)
  }

  // 数据初始化
  const init = async () => {
    const res = await CartList('include=goods').catch((err) => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setLoadingCode(2)
      if (err.status === 401) Toast.show({icon: 'success', content: '请先登录呀', duration: 1500, maskClickable: false, afterClose: () => {
        navigate('/login', {state: {fromPath: 'shopcart'}})
      }})
    })

    try {
      if(res?.status === 200) {
        setFlag(false)
        setList(res.data.data, (data: []) => { // 购物车列表
          const id = data.filter((item: {is_checked: number}) => item.is_checked === 1).map((itemB: {id: number}) => itemB.id)
          setValue(id, (dataB: CheckboxValue[]) => { // 选中的商品
            totalPrice(data, dataB) // 总价
            if(data.length === dataB.length) { // 购物车数量 === 选中的数量 则是全选
              setCheckAll(true)
            }
          }) 
        })
      }
    } catch (error) {
      console.log(error)
    }
  }   
  
  useEffect(() => {
    init()
  }, [cartNum]) // 当购买新的产品时, 购物车数量发生改变了, 购物车页面才会重新请求数据

  // 用户没有登录进入到购物车页面, 是会跳转到登录页面
  // 重点：用户先后进入到购物车页面 然后再从购物车页面进入到登录页面 那么useEffect已经执行过一次了，但因为没有登录报错了 数据没有请求回来
  // 那从登录页面在返回购物车页面 是不会在执行useEffect的了 只会执行缓存组件被激活的函数
  // 所以需要在useActivate重新请求数据, 但因为缓存组件函数每次都会触发， 所以得想办法 只能让他执行一次
  // 用了count计数器, 只有count === 1 才请求数据
  useActivate(() => {
    setFlag(false)
    if(count === 1) {
      init()
    }
  })

  useUnactivate(() => {
    setCount(count + 1)
  })

  // 购物车产品遍历
  const getList = () => {
    return list.map((item: itemType) => {
      return (
        <SwipeAction key={item.id} rightActions={[{key: 'delete', text: '删除', color: 'danger', onClick: () => deleteProduct(item.id)}]}>
          <div className={style.item} key={item.id}>
            <div className={style.itemLeft}>
            <div className={style.radio}>
              <Checkbox.Group value={value} onChange={(item: CheckboxValue[]) => checkResult(item)}>
                <Checkbox value={item.id}></Checkbox>
              </Checkbox.Group>
            </div>
            <div className={style.img}>
               <Image width={80} height={80} src={item.goods.cover_url}/>
            </div>
            <div className={style.msg}>
               <p>{item.goods.title}</p>
               <p>￥{item.goods.price}</p>
            </div>
            </div>
            <div className={style.itemRight}>
            <div className={style.stock}>库存: {item.goods.stock === 0 ? 0 : item.goods.stock - item.num}</div>
            <Stepper min={1} step={1} defaultValue={item.num} max={item.goods.stock} onChange={(value) => numChange(value, item.id)}/>
            </div>
          </div> 
        </SwipeAction>
      )
    })
  }

  // 点击产品单选
  const checkResult = (item: CheckboxValue[]) => {
    setValue(item, (data: []) => {
      if(data.length === list.length) {
        setCheckAll(true)
      } else {
        setCheckAll(false)
      }
      totalPrice(list, data)
    })
    checkedCart({cart_ids: item}) // 购物车后台改变选中
  }

  // 点击全选
  const getCheckAll = (flag: boolean) => {
    if(flag) {
      setValue(list.map((item: {id: number}) => item.id), (data: []) => {
        totalPrice(list, data)
      })
      setCheckAll(true)
      checkedCart({cart_ids: list.map((item: {id: number}) => item.id)}) // 购物车后台改变选中
    } else {
      setValue([])
      setCheckAll(false)
      // totalPrice(list, [])
      setTotal(0)
      checkedCart({cart_ids: []}) // 购物车后台改变选中
    }
  }

  // 修改单个产品数量
  const numChange = async (num: any, id: string) => {
    const res = await UpdateNum(id, {num: num}).catch((err) => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setLoadingCode(2)
    })

    try {
      if(res?.status === 204) {
       list.filter((item: {id: any}) => item.id ===id)[0].num = num
       totalPrice(list, value)
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 删除产品
  const deleteProduct = async (id: any) => {
   Dialog.confirm({ content: '确定要删除吗', onConfirm: async () => {
      const res = await DeleteProduct(id).catch((err) => {
        if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setLoadingCode(2)
      })

      try {
       if(res?.status === 204) {
        dispatch(cartNumAsync())
        Toast.show({ icon: 'success', content: "删除成功", maskClickable: false, duration: 1500, afterClose: () => {
          setList(list.filter((item: {id: number}) => item.id !== id), (data: []) => { // 更新购物车商品
            setValue(value.filter((item: number) => item !== id), (dataB: []) => { // 更新选中的商品
              if(data.length === dataB.length) { // 如果购物车商品数量 和 更新选中的商品的数量一致 则是全选
                setCheckAll(true)
              }
              totalPrice(data, dataB) // 重新计算价格
            })
          })
        }})         
       }
      } catch (error) {
        console.log(error)
      }
   }})
  }

  return (
    <>
     {/* 头部信息 */}
     <HeaderView title='购物车' backIcon={false} backPath=''></HeaderView>

     {/* 内容信息 */}
     <div className={style.content}>
       {getList()}
     </div>

     {/* 全选 */}
     <div className={style.all}>
        <Checkbox checked={checkAll} onChange={(flag) => getCheckAll(flag)} style={{'--icon-size': '18px', '--font-size': '14px'}}>全选</Checkbox>
        <div className={style.pay}>
          <span>￥{total}</span>
          <Button size='small' color='danger'>结算</Button>
        </div>
     </div>

     {/* 底部tabbar */}
     <Bottom></Bottom>

     {/* 暂无数据 */}
     {list.length === 0 ? <p className={style.no}>暂无数据</p> : ''}

     {/* 加载中或者加载超时 */}
     {flag && <LoadingView loadingCode={loadingCode}></LoadingView>}
    </>
  )
}

export default ShopCart